<template>
  <div v-loading="loading" class="container">
    <el-tree :data="depts" :props="defaultProps" default-expand-all :expand-on-click-node="false">
      <!-- 布局组件 el-row-el-col -->
      <template v-slot="{ data }">
        <el-row style="width: 100%; height: 40px;" align="middle" type="flex">
          <el-col>{{ data.name }}</el-col>
          <el-col>
            <el-row type="flex" justify="end">
              <span class="username">{{ data.managerName }}</span>
              <el-dropdown @command="operateDept($event,data.id)">
                <span class="username">操作<i class="el-icon-arrow-down" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </el-col>
        </el-row>
      </template>

    </el-tree>
    <addDepts ref="addDept" :show-dialog.sync="showDialog" :department-id="departmentId" @updateDept="getDepartment" />
  </div>
</template>
<script>
import { getDepartmentAPI } from '@/api'
import { departmentTreeData } from '@/utils'
import { addDepts } from '@/views/department/components'
export default {
  name: 'Department',
  components: {
    addDepts
  },
  data() {
    return {
      showDialog: false,
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      departmentId: null
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      this.loading = true
      this.depts = departmentTreeData(await getDepartmentAPI(), 0)
      this.loading = false
    },
    async operateDept(type, id) {
      if (type === 'add') {
        this.showDialog = true
        this.departmentId = id
      } else if (type === 'edit') {
        // 编辑场景
        // Props的渲染是异步的
        this.showDialog = true // 编辑场景下显示弹层
        this.departmentId = id // 给data赋值 传递给props
        // nextTick => 微任务 异步 nextTick会等到组件的上一次更新完成之后执行
        // this.$nextTick(() => {
        //   // 回调函数会等到上一次更新完成之后
        //   this.$refs.addDept.getDepartMentDetail()
        // })
        await this.$refs.addDept.getDepartMentDetail(id)
      }
    }
  }
}

</script>
<style scoped>
  .app-container {
    padding: 20px 150px;
  }
  .username {
    margin-right: 10px;
    font-size: 14px;
  }
</style>
